package com.lefu.es.system;

import android.app.AlertDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.lefu.es.blenew.bean.BluetoothLeDevice1;
import com.lefu.es.blenew.helper.BleHelper1;
import com.lefu.es.constant.AppData;
import com.lefu.es.constant.BluetoolUtil;
import com.lefu.es.constant.UtilConstants;
import com.lefu.es.db.RecordDao;
import com.lefu.es.db2.MacDao;
import com.lefu.es.entity.DeviceMacDao;
import com.lefu.es.entity.Records;
import com.lefu.es.entity.UserModel;
import com.lefu.es.event.NoRecordsHarmBabysEvent;
import com.lefu.es.event.ReFlushBabyEvent;
import com.lefu.es.service.ExitApplication;
import com.lefu.es.service.TimeService;
import com.lefu.es.util.LogUtil;
import com.lefu.es.util.MoveView;
import com.lefu.es.util.MyUtil;
import com.lefu.es.util.SPUtil;
import com.lefu.es.util.StringUtils;
import com.lefu.es.util.UtilTooth;
import com.lefu.es.view.MyTextView3;
import com.lefu.es.view.MyTextView5;
import com.wellness.scale.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
抱婴模式秤
* */
public class BabyScaleNewActivity extends BaseNotAutoBleActivity {

    protected UserModel babyUser = null;
    protected Records lastRecord = null;
    @Bind(R.id.setting_menu)
    RelativeLayout set;
    @Bind(R.id.harmbaby_menu)
    RelativeLayout up_scale;
    @Bind(R.id.back_ly)
    LinearLayout backBtn;
    @Bind(R.id.bluetooth_status)
    AppCompatTextView bluetoothStatusTx;
    @Bind(R.id.blue_img)
    ImageView blue_img;
    @Bind(R.id.weith_value_tx)
    MyTextView5 weithValueTx;
    @Bind(R.id.user_name)
    AppCompatTextView userNameTx;
    @Bind(R.id.user_header)
    SimpleDraweeView userHeadImg;
    @Bind(R.id.targe_tx)
    TextView targetTx;
    @Bind(R.id.compare_last_tx)
    MyTextView3 compare_tv;
    @Bind(R.id.weith_status)
    TextView weithStatus;
    @Bind(R.id.unti_tv)
    TextView unit_tv;
    /*BMI
   *-----------------
   */
    @Bind(R.id.face_img_bmi)
    ImageView face_img_bmi;
    @Bind(R.id.face_img_bmi_ll)
    LinearLayout face_img_bmi_ll;
    @Bind(R.id.bmi_critical_point1)
    TextView bmi_critical_point1;
    @Bind(R.id.bmi_critical_point2)
    TextView bmi_critical_point2;
    @Bind(R.id.bmi_critical_point3)
    TextView bmi_critical_point3;
    @Bind(R.id.bmi_biaoz)
    AppCompatTextView bmi_biaoz;
    @Bind(R.id.bmi_index_tx)
    AppCompatTextView bmiIndex;
    private boolean isElectronic = false;

    /*** 初始化页面 ***/
    private Handler initHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: //初始化界面
                    Records lastRecord = (Records) msg.obj;
                    if (null != lastRecord) {
                        localData(lastRecord, babyUser);
                        initBodyBar(babyUser, lastRecord);
                    }
                    break;
                case 2:
                    localData(null, babyUser);
                    initBodyBar(babyUser, null);
                    break;
            }
        }
    };

    /**
     * 数据处理
     *
     * @param readMessage
     * @param i
     */
    private List<DeviceMacDao> macArrayList = MacDao.queryAll();
    private long firstTime = 0;
    private long twoTime = 0;
    private int timeIndex = 1;
    private float lastWeight;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Records data = (Records) msg.obj;
                    saveBabyData(data);
                    break;
            }
        }
    };

    private void saveBabyData(Records data) {
        if (isOpenBabyScale && null != data && data.getRweight() > 0) {
            if (null == receiveRecord || timeIndex == 1) {
                timeIndex = 2;
                firstTime = System.currentTimeMillis();
                lastWeight = data.getRweight();
                LogUtil.e("***第一次大人称重*lastWeight**" + lastWeight + "***第一次次时间***" + firstTime);
                receiveRecord = data;
                showDownCountDataDialog(getString(R.string.harm_baby_onscale_waring));
                return;
            } else {
                LogUtil.e("==========接收到抱婴数据了===============");
                twoTime = System.currentTimeMillis() - firstTime;
                LogUtil.e("***第二次大人抱小孩称重*getRweight()**" + data.getRweight() + "***第二次时间***" + twoTime);
                if (twoTime < 4000) {
                    LogUtil.e("测试间隔时间太短");
                    return;
                }
                stopScan();
                disConnect();
                scanHandler.removeCallbacks(scanThread1);
                LogUtil.e("****停止扫描，断开连接****");
                float weight = data.getRweight() - lastWeight;
                //關閉倒計時狂
                if (null != downCountDialog) {
                    downCountDialog.dismiss();
                    downCountDialog = null;
                    /***广播数据断开**/
                    if (mDeviceName.equals(AppData.LF_SCALE)) {
                        bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_not_connected));
                        stopScan();
                        disConnect();
                        scanHandler.removeCallbacks(scanThread1);
                    }
                }
                if (null != time) {
                    time.cancel();
                    time = null;
                }
                if (weight > 0) {
                    //保存 婴体重
                    try {
                        AppData.hasCheckData = true;
                        if (!BluetoolUtil.bleflag)
                            TimeService.setIsdoing(true);
                        data.setRweight(weight);
                        data.setSweight(String.valueOf(weight));
                        data.setScaleType(UtilConstants.BABY_SCALE);
                        //更新界面
                        if (null != lastRecord) {
                            float compare = data.getRweight() - lastRecord.getRweight();
                            data.setCompareRecord((UtilTooth.myround(compare)) + "");
                            LogUtil.e("***婴儿车前后重量相差***" + compare);
                            if (Math.abs(compare) >= 2) {
                                //替换当前页面最后的测量记录
                                lastRecord = data;
                                stopScan();
                                disConnect();
                                scanHandler.removeCallbacks(scanThread1);
                                askForSaveExceptionData(data);
                                return;
                            }
                        } else {
                            data.setCompareRecord((UtilTooth.myround(weight)) + "");
                        }
                        //替换当前页面最后的测量记录
                        lastRecord = data;
                        //通知界面更新
                        Message message = initHandler.obtainMessage(1);
                        message.obj = data;
                        initHandler.sendMessage(message);
                        //保存记录
                        RecordDao.handHarmBabyData(recordService, data, babyUser);
                        LogUtil.e("***保存记录*data****" + data);
                        if (null != mBluetoothLeService) {
                            timeIndex = 1;
                            LogUtil.e("****断开蓝牙****");
                            scanHandler.removeCallbacks(scanThread1);
                            mScanner.stopScan();
                            mBluetoothLeService.disconnect();
                        }
                        //重置
                        timeIndex = 1;
                        receiveRecord = null;
                        //lastRecord = null;
                        isOpenBabyScale = false;
                    } catch (Exception e) {
                        LogUtil.e("***保存用户测量数据异常***" + e.getMessage());
                        stopScan();
                        disConnect();
                        scanHandler.removeCallbacks(scanThread1);
                        //重置
                        timeIndex = 1;
                        receiveRecord = null;
                        //lastRecord = null;
                        isOpenBabyScale = false;
                    }
                } else {
                    //测量有误，抱婴后还比之前轻了
                    if (null != mBluetoothLeService) {
                        timeIndex = 1;
                        LogUtil.e("****断开蓝牙****");
                        mScanner.stopScan();
                        mBluetoothLeService.disconnect();
                    }
                    //重置
                    receiveRecord = null;
                    //lastRecord = null;
                    isOpenBabyScale = false;
                    Toast.makeText(BabyScaleNewActivity.this,
                            getString(R.string.mesure_error_harmbaby),
                            Toast.LENGTH_LONG).show();
                }
            }
        }else{
            stopScan();
            disConnect();
            scanHandler.removeCallbacks(scanThread1);
        }
    }

    /**
     * 构建实例
     *
     * @param context
     * @param baby
     * @return
     */
    public static Intent createIntent(Context context, UserModel baby) {
        Intent intent = new Intent(context, BabyScaleNewActivity.class);
        intent.putExtra("baby", baby);
        return intent;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        finish();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baby_scale_new);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        Serializable serializable = getIntent().getSerializableExtra("baby");
        if (null == serializable) {
            Toast.makeText(BabyScaleNewActivity.this, getString(R.string.choice_a_baby), Toast.LENGTH_LONG).show();
            finish();
        } else {
            babyUser = (UserModel) serializable;
            initView(babyUser);

            Toast.makeText(BabyScaleNewActivity.this, getString(R.string.click_onscale_waring),
                    Toast.LENGTH_LONG).show();
        }
        TextView harmbaby_cicle = (TextView) findViewById(R.id.harmbaby_cicle);
        harmbaby_cicle.setText(R.string.shangchen);
        ExitApplication.getInstance().addActivity(this);
    }

    private void initView(UserModel babyUser) {
        if (null != babyUser) {
            if (!TextUtils.isEmpty(babyUser.getPer_photo())) {
                userHeadImg.setImageURI(Uri.fromFile(new File(babyUser.getPer_photo())));
            } else {
                LogUtil.e("****显示默认的小孩头像***");
                userHeadImg.setImageResource(R.drawable.baby_default);
            }
            userNameTx.setText(babyUser.getUserName());
            if (babyUser.getDanwei().equals(UtilConstants.UNIT_LB)
                    || babyUser.getDanwei().equals(UtilConstants.UNIT_FATLB)
                    || babyUser.getDanwei().equals(UtilConstants.UNIT_ST)) {
                targetTx.setText(UtilTooth.lbozToString(this, babyUser.getTargweight()));
            } else {
                targetTx.setText(UtilTooth.keep1Point3(babyUser.getTargweight()) + "kg");
            }
            //初始化界面参数
            initViewData(babyUser);
        }
    }

    public void initViewData(final UserModel babyUser) {
        if (null != babyUser) {
            //获取最后一次测量记录
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        lastRecord = recordService.findLastRecords(babyUser.getId());
                        if (null != lastRecord) {
                            Message message = initHandler.obtainMessage(1);
                            message.obj = lastRecord;
                            initHandler.sendMessage(message);
                        } else {
                            Message message = initHandler.obtainMessage(2);
                            initHandler.sendMessage(message);
                        }
                    } catch (Exception e) {
                        LogUtil.e("初始化抱婴界面失败：" + e.getMessage());
                    }
                }
            });
            thread.start();
        }
    }

    @Override
    public void updateConnectionState(int resourceId) {
        switch (resourceId) {
            case R.string.disconnected:
                //bluetoothStatusTx.setTextColor(getColor(R.color.shadow));
                bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_not_connected));
                //blue_img.setBackground(getDrawable(R.drawable.blue_gray_icon));
                break;

            case R.string.connected:
                // bluetoothStatusTx.setTextColor(getColor(R.color.white));
                bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_connected));
                //blue_img.setBackground(getDrawable(R.drawable.blue_icon));
                break;
        }
    }

    @Override
    public void discoverBleService() {
        if (null != mDeviceName && (mDeviceName.toLowerCase().startsWith("heal")
                || mDeviceName.toLowerCase().startsWith("yu")
                || (null != mDeviceName && mDeviceName.equals(AppData.LF_SCALE)))) {
            isElectronic = false;
            try {
                if (null != mBluetoothLeService) {
                    final BluetoothGattCharacteristic characteristic =
                            mBluetoothLeService.getCharacteristicNew(mBluetoothLeService.getSupportedGattServices(), "fff4");
                    mBluetoothLeService.setCharacteristicIndiacate(characteristic, true);
                    //发送用户组数据
                    String unit = "00";
                    if (babyUser.getDanwei().equals(UtilConstants.UNIT_ST)) {
                        unit = "02";
                    } else if (babyUser.getDanwei().equals(UtilConstants.UNIT_LB)) {
                        unit = "01";
                    } else {
                        unit = "00";
                    }
                    // 获取用户组
                    String p = "00";
                    if (null != UtilConstants.CURRENT_USER) {
                        p = UtilConstants.CURRENT_USER.getGroup().replace("P", "0");
                    }
                    // 获取 校验位
                    String xor = Integer.toHexString(StringUtils.hexToTen("fd") ^ StringUtils.hexToTen("37") ^ StringUtils.hexToTen(unit) ^ StringUtils.hexToTen(p));
                    LogUtil.e("****发送新称数据：" + "fd37" + unit + p + "000000000000" + xor);
                    // 发送数据
                    if (isOpenBabyScale)
                        BleHelper1.getInstance().sendDateToScale(mBluetoothLeService, "fd37" + unit + p + "000000000000" + xor);
                }
            } catch (Exception e) {
                LogUtil.e("***Exception e-->"+e.getLocalizedMessage());
                e.printStackTrace();
            }
        } else {
            if (null != mDeviceName && (mDeviceName.toLowerCase().startsWith("electronic"))) {
                isElectronic = true;
            }
            if (isOpenBabyScale)
                BleHelper1.getInstance().sendDateToScale(mBluetoothLeService, MyUtil.getUserInfo());
        }
    }

    private String lastReadMessage;
    @Override
    public void receiveBleDataBaby(String readMessage, BluetoothLeDevice1 device) {
        if (mDeviceAddress == null || mDeviceName == null) {
            if (device != null) {
                mDeviceAddress = device.getAddress();
                mDeviceName = device.getName();
            }
        }
        LogUtil.e("**readMessage**" + readMessage +"***mac-->"+mDeviceAddress);
        if (TextUtils.isEmpty(readMessage)) {
            /***广播数据断开**/
            if (mDeviceName.equals(AppData.LF_SCALE)&&bluetoothStatusTx!=null) {
                bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_not_connected));
            }
            return;
        }

        //双向通道
        if (isElectronic && readMessage.length()==34){
            UtilConstants.CURRENT_SCALE = UtilConstants.BODY_SCALE;
            LogUtil.e("***readMessage-->" + readMessage);
            String lastStr = readMessage.substring(32,34);
            LogUtil.e("***lastStr-->" + lastStr);
            if (lastStr.equals("f1")){
                MyUtil.setProcessWeightData0(BabyScaleNewActivity.this, readMessage.substring(0, 22),
                        weithValueTx, unit_tv, UtilConstants.CURRENT_USER.getDanwei(), true);
                LogUtil.e("***过程数据-->" + readMessage);
            }else if (lastStr.equals("f0") && (TextUtils.isEmpty(lastReadMessage)||!lastReadMessage.equals(readMessage)) ){
                if(System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000) {
                    UtilConstants.receiveDataTime = System.currentTimeMillis();
                    lastReadMessage = readMessage;
                    dueData(readMessage, 0);
                    LogUtil.e("***锁定数据-->" + readMessage);
                }
            }else{
                if(System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000) {
                    UtilConstants.receiveDataTime = System.currentTimeMillis();
                    lastReadMessage = readMessage;
                    dueData(readMessage, 0);
                    LogUtil.e("***锁定数据-->" + readMessage);
                }
            }
            return;
        }

        if (!isOpenBabyScale) {
            return;
        }

        /****兼容旧版本**起*/
        if (readMessage.startsWith("0306")) {
            if ((System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000)) {
                LogUtil.e("**接下来收到的数据要兼容旧版本*readMessage**" + readMessage);
                receiveRecord = MyUtil.parseZuKangMessage(this.recordService, readMessage, UtilConstants.CURRENT_USER);
                LogUtil.e("**receiveRecord**" + receiveRecord);
                Message msg1 = handler.obtainMessage(0);
                msg1.obj = receiveRecord;
                handler.sendMessage(msg1);
            }
            return;
        }
        /****兼容旧版本**终*/

        //测脂错误
        if (readMessage.equals(UtilConstants.ERROR_CODE)) {
            if (babyUser.getDanwei().equals(UtilConstants.UNIT_ST) || babyUser.getDanwei().equals(UtilConstants.UNIT_LB)) {
                //Toast.makeText(BabyScaleNewActivity.this, getString(R.string.user_data_error), Toast.LENGTH_LONG).show();
            } else {
                //Toast.makeText(BabyScaleNewActivity.this, getString(R.string.user_data_error_lb), Toast.LENGTH_LONG).show();
            }
            LogUtil.e("***年龄：10-100  身高：100-220cm 返回**");
            //return;
        } else if (readMessage.equals(UtilConstants.ERROR_CODE_TEST)) {
            Toast.makeText(BabyScaleNewActivity.this, getString(R.string.scale_measurement_error), Toast.LENGTH_LONG).show();
            return;
        }
        //处理不同类型的秤
        boolean newScale = false;
        try {
            if ((readMessage.startsWith("0306"))) {//阿里秤
                newScale = true;
                UtilConstants.CURRENT_SCALE = UtilConstants.BODY_SCALE;
            } else {
                newScale = false;
            }
            if (null != mDeviceName && mDeviceName.toLowerCase().startsWith("health")
                    || (null != mDeviceName && mDeviceName.equals(AppData.LF_SCALE))) { //新的DL Scale

                if (mDeviceName.equals(AppData.LF_SCALE) && bluetoothStatusTx!=null) {
                    bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_connected));
                }

                //CF 88 13 00 14 00 00 00 00 00 40
                if (RecordDao.isLockData(readMessage)) {
                    if ((System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000)) {
                        UtilConstants.receiveDataTime = System.currentTimeMillis();
                        dueData(readMessage, 3);
                    }
                } else {
                    dueData(readMessage, 2);
                }
            } else {
                LogUtil.e("****判断是不是两次连续的数据**newScale-->"+newScale+"***readMessage-->"+readMessage);
                /**判断是不是两次连续的数据*/
                if (readMessage.length() > 31 && (System.currentTimeMillis() - UtilConstants.receiveDataTime > 1000)) {
                    UtilConstants.receiveDataTime = System.currentTimeMillis();
                    if (newScale) {
                        dueData(readMessage, 1);
                    } else {
                        if (readMessage.equals(UtilConstants.ERROR_CODE)) {
                            if (babyUser.getDanwei().equals(UtilConstants.UNIT_ST) || babyUser.getDanwei().equals(UtilConstants.UNIT_LB)) {
                                //Toast.makeText(BabyScaleNewActivity.this, getString(R.string.user_data_error), Toast.LENGTH_LONG).show();
                            } else {
                                //Toast.makeText(BabyScaleNewActivity.this, getString(R.string.user_data_error_lb), Toast.LENGTH_LONG).show();
                            }
                            LogUtil.e("***年龄：10-100  身高：100-220cm 返回**");
                            //return;
                        } else if (readMessage.equals(UtilConstants.ERROR_CODE_TEST)) {
                            //Toast.makeText(BabyScaleNewActivity.this, getString(R.string.scale_measurement_error), Toast.LENGTH_LONG).show();
                            return;
                        }
                        if (readMessage.equals(UtilConstants.ERROR_CODE_GETDATE)) {
                            openErrorDialog("2");
                            return;
                        }
                        if ((readMessage.startsWith("c") && readMessage.length() > 31)) {
                            LogUtil.e("*****处理16字节数据***readMessage-->" + readMessage);
                            dueData(readMessage, 0);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("****解析数据异常**e-->" + e.getMessage());
        }
    }

    @Override
    protected void saveDataCallBack(Records records) {
        initBodyBar(babyUser, records);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onStop() {
        if (scanHandler!=null && scanThread1!=null){
            scanHandler.removeCallbacks(scanThread1);
        }
        super.onStop();
    }

    private void dueData(String readMessage, int i) {
        Records records = null;
        if (0 == i) {//旧秤
            records = MyUtil.parseMessage(this.recordService, readMessage);
            if (records != null) {
                String scaleType = records.getScaleType();
                LogUtil.e("****当前秤类型-->" + scaleType);
            }
            LogUtil.e("****解析体重-->" + records.getRweight());
            Message msg1 = handler.obtainMessage(0);
            msg1.obj = records;
            handler.sendMessage(msg1);
        } else if (1 == i) {//阿里秤
            records = MyUtil.parseZuKangMeaage(this.recordService, readMessage, babyUser);
            if (records != null) {
                String scaleType = records.getScaleType();
                LogUtil.e("*****当前秤类型-->" + scaleType);
                if (macArrayList.isEmpty()) {
                    for (int i1 = 0; i1 <= macArrayList.size(); i1++) {
                        LogUtil.e("****当前没有绑定mac-->"+macArrayList.get(i1));
                        if ("cf".equals(scaleType)) {
                            bindScale("2");
                        } else {
                            bindScale("1");
                        }
                    }
                } else {
                    for (int i1 = 0; i1 < macArrayList.size(); i1++) {
                        LogUtil.e("****当前没有绑定mac-->"+macArrayList.get(i1));
                        if ("cf".equals(scaleType)) {
                            bindScale("2");
                        } else {
                            bindScale("1");
                        }
                    }
                }
            }
            LogUtil.e("****解析体重-->" + records.getRweight());
            Message msg1 = handler.obtainMessage(0);
            msg1.obj = records;
            handler.sendMessage(msg1);
        } else if (2 == i) {//新称过程数据
            MyUtil.setProcessWeightData(BabyScaleNewActivity.this, readMessage, weithValueTx, babyUser.getDanwei(), true);
        } else if (3 == i) {//新秤锁定数据
            records = MyUtil.parseDLScaleMessage(this.recordService, readMessage, babyUser);
            if (records != null) {
                String scaleType = records.getScaleType();
                LogUtil.e("****当前秤类型**scaleType-->" + scaleType);
                if (macArrayList.isEmpty()) {
                    for (int i1 = 0; i1 <= macArrayList.size(); i1++) {
                        LogUtil.e("当前没有绑定mac-->"+macArrayList.get(i1));
                        if ("cf".equals(scaleType)) {
                            bindScale("2");
                        } else {
                            bindScale("1");
                        }
                    }
                } else {
                    for (int i1 = 0; i1 < macArrayList.size(); i1++) {
                        LogUtil.e("当前没有绑定mac-->"+macArrayList.get(i1));
                        if ("cf".equals(scaleType)) {
                            bindScale("2");
                        } else {
                            bindScale("1");
                        }
                    }
                }
            }
            Message msg1 = handler.obtainMessage(0);
            msg1.obj = records;
            handler.sendMessage(msg1);
        }
    }

    private void bindScale(final String type) {
        LogUtil.e("****mac_address-->" + mDeviceAddress+"****type-->"+type);
        /**保存蓝牙数据实体类***/
        DeviceMacDao deviceMacDao = new DeviceMacDao();
        deviceMacDao.setDeviceName(mDeviceName);
        deviceMacDao.setDeviceType(type);
        deviceMacDao.setMac(mDeviceAddress);
        MacDao.insertMac(deviceMacDao);
        SPUtil.put(BabyScaleNewActivity.this, "mac_flag", 0);
    }

    /**
     * 初始化 圆圈参数
     *
     * @param
     */
    private void localData(Records record, UserModel user) {
        if (null == user) return;
        if (null == record) {
            if (user.getDanwei().equals(UtilConstants.UNIT_LB)
                    || user.getDanwei().equals(UtilConstants.UNIT_FATLB)
                    || user.getDanwei().equals(UtilConstants.UNIT_ST)) {
                weithValueTx.setTexts("0lb:0oz", null);
                compare_tv.setTexts("0.0 lb", null);
                if (null != unit_tv) {
                    unit_tv.setText("");
                }
            } else {
                compare_tv.setTexts("0.0 kg", null);
                weithValueTx.setTexts("0.0", null);
                if (null != unit_tv) {
                    unit_tv.setText(this.getText(R.string.kg_danwei));
                }
            }
        } else {
            if (user.getDanwei().equals(UtilConstants.UNIT_LB)
                    || user.getDanwei().equals(UtilConstants.UNIT_FATLB)
                    || user.getDanwei().equals(UtilConstants.UNIT_ST)) {
                weithValueTx.setTexts(UtilTooth.lbozToString(BabyScaleNewActivity.this, record.getRweight()), null);
                if (null != unit_tv) {
                    unit_tv.setText("");
                }
            } else {
                weithValueTx.setTexts(UtilTooth.keep1Point(record.getRweight()), null);
                if (null != unit_tv) {
                    unit_tv.setText(this.getText(R.string.kg_danwei));
                }
            }
            String sex = user.getSex();
            if (TextUtils.isEmpty(sex) || "null".equalsIgnoreCase(sex)) sex = "1";
            int gender = Integer.parseInt(sex);
            LogUtil.e("*****小孩的年龄**ageYear-->" + user.getAgeYear());
            weithStatus.setText(MoveView.babyWeightString(user.getAgeYear(), gender, user.getBheigth(), record.getRweight(), this));

            if (user.getDanwei().equals(UtilConstants.UNIT_KG)) {
                if (null == record.getCompareRecord() || "".equals(record.getCompareRecord())) {
                    //compare_tv.setTexts("0.0", null);
                    compare_tv.setTexts("0.0 " + this.getText(R.string.kg_danwei), null);
                } else {
                    BigDecimal b = new BigDecimal(Double.parseDouble(record.getCompareRecord()));
                    float cr = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                    if (cr > 0) {
                        compare_tv.setTexts("↑" + UtilTooth.myroundString3(Math.abs(cr) + "") + this.getText(R.string.kg_danwei), null);
                    } else if (cr < 0) {
                        compare_tv.setTexts("↓" + UtilTooth.myroundString3(Math.abs(cr) + "") + this.getText(R.string.kg_danwei), null);
                    } else {
                        compare_tv.setTexts(UtilTooth.myroundString3(record.getCompareRecord() + "") + this.getText(R.string.kg_danwei), null);
                    }
                }
            } else if (user.getDanwei().equals(UtilConstants.UNIT_LB)
                    || user.getDanwei().equals(UtilConstants.UNIT_FATLB)
                    || user.getDanwei().equals(UtilConstants.UNIT_ST)) {
                if (null == record.getCompareRecord() || "".equals(record.getCompareRecord().trim())) {
                    record.setCompareRecord("0");
                    compare_tv.setTexts("0.0 " + " " + this.getText(R.string.lboz_danwei), null);
                } else {
                    float cr = Float.parseFloat(record.getCompareRecord());
                    if (cr > 0) {
                        compare_tv.setTexts("↑" + UtilTooth.lbozToString(BabyScaleNewActivity.this, record.getRweight()), null);
                    } else if (cr < 0) {
                        compare_tv.setTexts("↓" + UtilTooth.lbozToString(BabyScaleNewActivity.this, record.getRweight()), null);
                    } else {
                        compare_tv.setTexts("0.0" + " " + this.getText(R.string.lboz_danwei), null);
                    }
                }
            } else {
                if (null == record.getCompareRecord() || "".equals(record.getCompareRecord())) {
                    compare_tv.setTexts("0.0", null);
                    compare_tv.setTexts("0.0 " + this.getText(R.string.kg_danwei), null);
                } else {
                    BigDecimal b = new BigDecimal(Double.parseDouble(record.getCompareRecord()));
                    float cr = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                    if (cr > 0) {
                        compare_tv.setTexts("↑" + UtilTooth.myroundString3(Math.abs(cr) + "") + this.getText(R.string.kg_danwei), null);
                    } else if (cr < 0) {
                        compare_tv.setTexts("↓" + UtilTooth.myroundString3(Math.abs(cr) + "") + this.getText(R.string.kg_danwei), null);
                    } else {
                        compare_tv.setTexts(UtilTooth.myroundString3(record.getCompareRecord() + "") + this.getText(R.string.kg_danwei), null);
                    }
                }
            }
        }
    }

    @OnClick(R.id.user_header)
    public void userHeaderClick() {
        if (null != mScanner) mScanner.stopScan();
        if (null != mBluetoothLeService) {
            mBluetoothLeService.disconnect();
        }
        startActivityForResult(UserBabyListActivity.createIntent(BabyScaleNewActivity.this, babyUser.getId()), 102);
    }

    @OnClick(R.id.blue_img)
    public void setBlueToothClick() {
        if (null != mScanner) mScanner.stopScan();
        if (null != mBluetoothLeService) {
            mBluetoothLeService.disconnect();
        }
    }

    @OnClick(R.id.bluetooth_status)
    public void setBlueToothTXClick() {
        if (null != mScanner) mScanner.stopScan();
        if (null != mBluetoothLeService) {
            mBluetoothLeService.disconnect();
        }
    }

    /*** 返回事件 ***/
    @OnClick(R.id.back_ly)
    public void backClick() {
        scanHandler.removeCallbacks(scanThread1);
        if (null != mScanner) mScanner.stopScan();
        if (null != mBluetoothLeService) {
            mBluetoothLeService.disconnect();
        }
        this.finish();
    }

    @OnClick(R.id.history_menu)
    public void historyMenuClick() {
        if (null != mScanner) mScanner.stopScan();
        if (null != mBluetoothLeService) {
            mBluetoothLeService.disconnect();
        }
        LogUtil.e("****进入历史baby-->" + babyUser.toString());
        startActivityForResult(RecordBabyListActivity.creatIntent(BabyScaleNewActivity.this, babyUser), 0);
    }

    @OnClick(R.id.harmbaby_menu)
    public void upScaleClick() {
        this.isOpenBabyScale = true;
        receiveRecord = null;
        showDownCountDataDialog(getString(R.string.adult_onscale_waring));
        //開啟藍牙掃描
        startScanBLE();
    }

    @OnClick(R.id.setting_menu)
    public void setMenuClick() {
        if (null != mScanner) mScanner.stopScan();
        if (null != mBluetoothLeService) {
            mBluetoothLeService.disconnect();
        }
        startActivity(BodyFatScaleSetActivity.creatIntent(BabyScaleNewActivity.this, babyUser));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ReFlushBabyEvent reFlushBabyEvent) {
        UserModel userModel = reFlushBabyEvent.getUserModel();
        if (null != userModel) {
            babyUser = userModel;
            initView(userModel);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(NoRecordsHarmBabysEvent noRecordsEvent) {
        if (null != babyUser) {
            //初始化界面参数
            initViewData(babyUser);
            initBodyBar(babyUser, null);
        }
    }

    /**
     * 初始化界面所有的进度条
     *
     * @param record
     */
    public void initBodyBar(UserModel user, Records record) {
        if (null != record && null != user) {
            // BMI
            LogUtil.e("****record.getRbmi()-->" + record.getRbmi());
            bmiIndex.setText(UtilTooth.keep1Point(record.getRbmi()));
            if (user.getAgeYear() > 5) {
                MoveView.bmi(BabyScaleNewActivity.this, face_img_bmi_ll, face_img_bmi, bmi_critical_point1,
                        bmi_critical_point2, bmi_critical_point3, bmi_biaoz, record.getRbmi());
            } else {
                MoveView.bmibaby(BabyScaleNewActivity.this, face_img_bmi_ll, face_img_bmi,
                        bmi_critical_point1, bmi_critical_point2, bmi_critical_point3, bmi_biaoz, record.getRbmi());
            }
        } else {
            bmiIndex.setText("0");
            MoveView.bmi(BabyScaleNewActivity.this, face_img_bmi_ll, face_img_bmi,
                    bmi_critical_point1, bmi_critical_point2, bmi_critical_point3, bmi_biaoz, 0);
        }
    }

    /*** 询问异常数据是否保存 ***/
    protected void askForSaveExceptionData(final Records records) {
        if (mDeviceName.equals(AppData.LF_SCALE)) {
            bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_not_connected));
            if (null != mBluetoothLeService) {
                LogUtil.e("****断开蓝牙****");
                mScanner.stopScan();
                mBluetoothLeService.disconnect();
            }
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(BabyScaleNewActivity.this);
        builder.setMessage(getString(R.string.receive_data_waring));
        builder.setNegativeButton(R.string.cancle_btn, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mDeviceName.equals(AppData.LF_SCALE)) {
                    bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_not_connected));
                }
                //启动 选择
                startActivityForResult(BabyChoiceForDataActivity.creatIntent(BabyScaleNewActivity.this, records), 103);
                dialog.dismiss();
            }
        });
        builder.setPositiveButton(R.string.ok_btn, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mDeviceName.equals(AppData.LF_SCALE)) {
                    bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_not_connected));
                }
                //通知界面更新
                Message message = initHandler.obtainMessage(1);
                message.obj = records;
                initHandler.sendMessage(message);
                //保存记录
                RecordDao.handHarmBabyData(recordService, lastRecord, babyUser);
                if (null != mBluetoothLeService) {
                    mScanner.stopScan();
                    mBluetoothLeService.disconnect();
                }
                //重置
                receiveRecord = null;
                //lastRecord = null;
                isOpenBabyScale = false;
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 102) {
            Bundle loginBundle = data.getExtras();
            if (null != loginBundle) {
                Serializable serializable = loginBundle.getSerializable("user");
                if (null != serializable) {
                    UserModel userModel = (UserModel) serializable;
                    babyUser = userModel;
                    initView(userModel);
                }
            }
        } else if (resultCode == 103) {
            Bundle loginBundle = data.getExtras();
            if (null != loginBundle) {
                Serializable serializable = loginBundle.getSerializable("user");
                if (null != serializable) {
                    UserModel user = (UserModel) serializable;
                    //替换当前页面最后的测量记录
                    babyUser = user;
                    //保存记录
                    RecordDao.handHarmBabyData(recordService, lastRecord, babyUser);
                    //通知界面更新
                    initView(babyUser);
                    //重置
                    if (null != mBluetoothLeService) {
                        mScanner.stopScan();
                        mBluetoothLeService.disconnect();
                    }
                    receiveRecord = null;
                    isOpenBabyScale = false;
                }
            }
        } else if (resultCode == 105) {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (scanHandler!=null&&scanThread1!=null){
            scanHandler.post(scanThread1);
        }
        stopScan();
        disConnect();
       /*if (mDeviceName.equals(AppData.LF_SCALE)){
            bluetoothStatusTx.setText(getResources().getText(R.string.connect_state_not_connected));
        }*/
    }

}